import { Upload } from 'antd';
import React, { useState, useEffect, useCallback } from 'react';
import { get } from 'lodash';
import { PlusOutlined } from '@ant-design/icons';
import styles from './styles.less';

interface BaseProps {
  placeholder?: string;
  fileName?: [];
  length?: number;
  onChange: (url: string) => void;
  onRemove?: (url: string) => void;
}

interface FileData {
  uid: string;
  name: string;
  status: string;
  response?: string;
  url: string;
}

interface stateData {
  fileList: FileData[];
}

const UploadFile: React.FC<BaseProps> = (props) => {
  const { fileName, onChange, length = 1, value } = props;

  const [state, setState] = useState<stateData>({
    fileList: [],
  });
  const { fileList } = state;

  // 处理文件回显
  useEffect(() => {
    if (fileName) {
      const list = fileName
        .filter((it: any) => it.url)
        .map(({ url, name, id }, uid) => ({
          id,
          uid: uid.toString(),
          name,
          status: 'done',
          url,
        }));
      setState({ fileList: list });
    }
  }, [fileName]);

  const onChangeHandler = useCallback((value: any) => {
    onChange && onChange(value)
  }, [])

  const uploadProps = {
    multiple: true,
    action: '/api/common/upload',
    fileList,
    headers: {
      Authorization: `Bearer ${sessionStorage.getItem('__TOKEN__')}`
    },
    listType: 'picture-card',
    onPreview: (file: any) => {
      console.log(file);
    },
    ...props,
    onRemove: (file: any) => {
      const { uid } = file;
      const list = [...fileList].filter((it) => it.uid !== uid);
      setState({ fileList: list });
      props.onRemove && props.onRemove(file);
    },
    onChange: ({ file, fileList: list }) => {
      if (file.status !== 'uploading') {
        let ans = [];
        if (length <= 1) {
          ans = get(file, ['response', 'data', 'url'], '');
        } else {
          list.forEach((el: any) => {
            if (el.response) {
              const { url, filename: name } = get(el, ['response', 'data'], {});
              ans.push({ url, name });
            } else {
              ans.push({ url: el.url, name: el.name, id: el.id });
            }
          });
        }
        if (ans) {
          onChangeHandler(ans);
        }
      }
      setState({ fileList: [...list] });
    },
  };
  console.log(fileList, 'fileList')

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div className="ant-upload-text">Upload</div>
    </div>
  );

  return (
    <Upload {...uploadProps} className={styles.upload}>
      {fileList.length < length && uploadButton}
    </Upload>
  );
};

export default UploadFile;
